# coding=gbk
import urllib2,urllib,cookielib,poster,re
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers

#ver 1 25/8/2013
#ver 2 01/09/2013
#ver 3 02/09/2013 get wpnonce release 1

class uploadException(Exception):
    def __init__(self,text):
        Exception.__init__(self)
        self.error = text

class uploadImg:
    loginurl = ""
    uploadurl = ""
    loginpara = {}
    wpnonce = ""
    __login = False
    isinit = False
    def __init__(self,loginurl,uploadurl,**loginpara):
        
        self.loginurl= loginurl
        self.uploadurl = uploadurl
        # init urllib2
        self.cj = cookielib.CookieJar()
        self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
        urllib2.install_opener(self.opener)

        self.loginpara = loginpara
    # login and get cookies
    def __login(self):
        logindata = urllib.urlencode(self.loginpara)
        req = urllib2.Request(self.loginurl,logindata)
        resp = urllib2.urlopen(req)
        respcode = resp.code
        if respcode == 200:
            return True
        else:
            return False
    # upload_init
    def __upload_init(self):
        # get wpnonce
        request = urllib2.Request(self.uploadurl)
        resp = urllib2.urlopen(request)
        result = re.search('<input\s+?type="hidden"\s+?id="_wpnonce"\s+?name="_wpnonce"\s+?value="(?P<wpnonce>.+?)"\s+?/>',resp.read())
        self.wpnonce = result.group("wpnonce")
        print self.wpnonce
        self.uploadopener = register_openers()
        self.uploadopener.add_handler(urllib2.HTTPCookieProcessor(self.cj))

    # init
    def init(self):
        if not self.__login() : 
            raise uploadException("login error")
            return False
        self.__upload_init()
        self.__login = True
        self.isinit = True
        return True
    # do_upload
    def do_upload(self,imgpath):
        if not self.__login : 
            raise uploadException("login unseccessful")
            return False
        postimage = poster.encode.MultipartParam.from_file("async-upload",imgpath)
        datagen,headers = multipart_encode([postimage,("post_id",0),("_wpnonce",self.wpnonce),("html-upload","上传")])
        request = urllib2.Request(self.uploadurl, datagen, headers)
        resp = urllib2.urlopen(request)
        return resp.code
'''
#for test
loginurl = "http://www.lzq179.com/wp-login.php"
uploadurl = "http://www.lzq179.com/wp-admin/media-new.php"
loginpara = {
    'log':'lzq',
    'pwd':'lizequn',
    'wp-submit':'',
    'testcookie':1,
    'redirect_to':'http://www.lzq179.com/wp-admin/'
    }
print "create"
test = uploadImg(loginurl,uploadurl,**loginpara)
print "init"
print test.init()
print "upload"
print test.do_upload("C:\\Users\\Zzz\\Desktop\\pic\\test.jpg")
print test.do_upload("C:\\Users\\Zzz\\Desktop\\pic\\test2.jpg")
'''
            
